package hexagon.security.core.domain;

import lombok.*;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.List;

/**
 * @author XueguiYuan
 * @version 1.0 (created time: 2016/12/3).
 */
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString(of = {"authority", "securityResource"})
@Entity
@Table(name = "resource_assignment")
public class ResourceAssignment extends SecurityAbstractEntity {

    @ManyToOne
    @JoinColumn(name = "authority_id")
    private Authority authority;

    @ManyToOne
    @JoinColumn(name = "security_resource_id")
    private SecurityResource securityResource;

    public static final Finder<Long, ResourceAssignment> find = new Finder<>(ResourceAssignment.class);

    @Override
    public String[] businessKeys() {
        return new String[]{"authority", "securityResource"};
    }

    public static ResourceAssignment findBySecurityResourceInAuthority(Authority authority, SecurityResource securityResource) {
        return find.where()
                .eq("authority", authority)
                .eq("securityResource", securityResource)
                .setMaxRows(1)
                .findUnique();
    }

    public static List<ResourceAssignment> findByAuthority(Authority authority) {
        return find.where()
                .eq("authority", authority)
                .findList();

    }

    public static List<ResourceAssignment> findBySecurityResource(SecurityResource securityResource) {
        return find.where()
                .eq("securityResource", securityResource)
                .findList();
    }

    public static List<SecurityResource> findSecurityResourceByAuthority(Authority authority) {
        return SecurityResource.find.where()
                .eq("resourceAssignments.authority", authority)
                .findList();
    }

    public static List<SecurityResource> findSecurityResourceByAuthority(Authority authority, SecurityResource.SecurityResourceType type) {
        return SecurityResource.find.where()
                .eq("resourceAssignments.authority", authority)
                .eq("type", type)
                .findList();
    }

    private boolean existed(Authority authority, SecurityResource securityResource) {
        return find.where()
                .eq("authority", authority)
                .eq("securityResource", securityResource)
                .findCount() > 0;
    }


}
